package com.yanboo.generator.config;

import cn.hutool.core.collection.ConcurrentHashSet;
import com.alibaba.druid.pool.DruidDataSource;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


public class DynamicRoutingDataSource extends AbstractConcurrentRoutingDataSource {

    private Set<String> hasCreateDataSource = new ConcurrentHashSet<>();

    private DataSourceFactory dataSourceFactory;

    public DynamicRoutingDataSource(DataSourceFactory dataSourceFactory){
        this.dataSourceFactory=dataSourceFactory;
    }
    @Override
    protected Object determineCurrentLookupKey() {
        String key = DataSourceKeyHolder.get();
        if (null == key) {
            return null;
        }
        if (hasCreateDataSource.contains(key)) {
            return key;
        }
        synchronized (this) {
            if (hasCreateDataSource.contains(key)) {
                return key;
            }
            DataSource dataSource = dataSourceFactory.createDataSource(key);
            if (dataSource==null){
                return null;
            }
            addDataSource(key, dataSource);
            hasCreateDataSource.add(key);
            return key;
        }
    }

}
